package com.klxedu.ms.gateway.security.access.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.klxedu.ms.gateway.core.json.BaseJsonObject;
import com.klxedu.ms.gateway.security.access.IResourceService;
import com.klxedu.ms.gateway.security.client.RoleAuthFeignClient;
import com.klxedu.ms.gateway.security.client.service.MenuOperation;
import com.klxedu.ms.gateway.security.client.service.RoleMenu;

public class DefaultResourceServiceImpl implements IResourceService {

	@Autowired
	private RoleAuthFeignClient roleAuthClient;

	@Override
	public Map<String, String[]> findAll() {
		HashMap<String, String[]> resRolesMap = new HashMap<>();
		BaseJsonObject<List<RoleMenu>> roleMenuResult = roleAuthClient.listRoleMenuOpt();
		List<RoleMenu> roleMenuList = roleMenuResult.getData();
		if (roleMenuList != null && !roleMenuList.isEmpty()) {
			for (RoleMenu roleMenu : roleMenuList) {
				String roleID = roleMenu.getRoleID();
				List<MenuOperation> optList = roleMenu.getMenuOptList();
				if (optList != null && !optList.isEmpty()) {
					for (MenuOperation opt : optList) {
						putRoles(resRolesMap, opt.getReqUrl() + "#" + opt.getReqMethod(), roleID);
					}
				}
			}
		}
		return resRolesMap;
	}

	private void putRoles(HashMap<String, String[]> resRolesMap, String key, String value) {
		String[] roles = resRolesMap.get(key);
		String[] newRoles = null;
		if (roles == null) {
			newRoles = new String[] { value };
			resRolesMap.put(key, newRoles);
		}else if(Arrays.asList(roles).contains(value)) {
			return;
		} else {
			newRoles = new String[roles.length + 1];
			System.arraycopy(roles, 0, newRoles, 0, roles.length);
			newRoles[newRoles.length - 1] = value;
		}
		resRolesMap.put(key, newRoles);
	}
}
